package com.iot.iotplus.accept;

import com.iot.iotplus.service.MessageService;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * @Description : MQTT接受服务的回调类
 */
@Component
public class MqttAcceptCallback implements MqttCallbackExtended {

    private static final Logger logger = LoggerFactory.getLogger(MqttAcceptCallback.class);
    @Autowired
    private MessageService messageService;

    @Autowired
    private MqttAcceptClient  mqttAcceptClient;

    @Autowired
    private MqttProperties mqttProperties;

    /**
     * 客户端断开后触发
     *
     * @param throwable
     */
    @Override
    public void connectionLost(Throwable throwable) {
        //logger.info("连接断开，可以重连");
        //if (MqttAcceptClient.client == null || !MqttAcceptClient.client.isConnected()) {
        //    logger.info("【emqx重新连接】....................................................");
        //    mqttAcceptClient.reconnection();
        //}
    }

    /**
     * 客户端收到消息触发
     *
     * @param topic       主题
     * @param mqttMessage 消息
     */
    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
        logger.info("【接收消息主题】:" + topic);
        logger.info("【接收消息Qos】:" + mqttMessage.getQos());
        logger.info("【接收消息内容】:" + new String(mqttMessage.getPayload()));
        messageService.saveMessage(new String(mqttMessage.getPayload()));
    }

    /**
     * 发布消息成功
     * @param token token
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
    String[] topics = token.getTopics();
    StringBuilder successLog = new StringBuilder();
    for (String topic : topics) {
        successLog.append("向主题【").append(topic).append("】发送消息成功！\n");
    }
    logger.info(successLog.toString());
    try {
        MqttMessage message = token.getMessage();
        if (message == null || message.getPayload() == null) {
            logger.warn("消息或负载为空，无法打印消息内容。");
            return;
        }
        byte[] payload = message.getPayload();
        String payloadString = new String(payload, StandardCharsets.UTF_8);
        logger.info("【消息内容】: " + payloadString);
    } catch (Exception e) {
        logger.error("处理消息时发生未知异常。异常信息: {}", e.getMessage());
    }
}


    /**
     * 连接emq服务器后触发
     *
     * @param b
     * @param s
     */
    @Override
    public void connectComplete(boolean b, String s) {
        logger.info("============================= 客户端【" + MqttAcceptClient.client.getClientId() + "】连接成功！=============================");
        // 以/#结尾表示订阅所有以test开头的主题
        // 订阅所有机构主题
        //mqttAcceptClient.subscribe(mqttProperties.getDefaultTopic(), 0);
    }
}